--global var
_rh = 0 --humidity
_t = 0 --temp
_timestamp = 0
_busy = false

_device = {title='node', desc='-',type='sht1x_v3', PIN='6666'}
_network = {ip='192.168.0.100', netmask='255.255.255.0', gateway='192.168.0.1', port=80}

local status_sntp

--set time
rtctime.set(1501812610, 0)
--read ip
local util = require('util')

local network = util.read_config('network', _network)
--dns
if (_network.dns_1 ~= nil) then
    net.dns.setdnsserver(_network.dns_1, 0)
else
    net.dns.setdnsserver(_network.gateway, 0)
end
if (_network.dns_2 ~= nil) then
    net.dns.setdnsserver(_network.dns_2, 1)
else
    net.dns.setdnsserver('114.114.114.114', 1)
end
--dhcp
if (wifi.getmode()==wifi.SOFTAP or wifi.getmode()==wifi.STATIONAP) then
    local p1, p2 = string.match(_network.ip,('(%d+.%d+.%d+.)(%d+)'))
    local p3 = tostring(tonumber(p2) + 1)
    local ip_server = p1..p3
    wifi.ap.dhcp.config({start=ip_server})
    wifi.ap.dhcp.start()
    wifi.ap.setip(network)
end
local device = util.read_config('device', _device)
_type = device.type
device = nil

--wifi event
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
    print('Connected to: ' .. T.SSID)
    if (network.ip ~= nil) then
        local ok = wifi.sta.setip(network)
        if (not ok) then
            print("\nip set failure")
        end
    end
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    if (network.ip ~= nil) then
        local name = 'n_'..string.gsub(wifi.sta.getmac(),':','')
        local mac = wifi.sta.getmac()
        local host = wifi.sta.gethostname()
        local config = {ip=network.ip, netmask=network.netmask, port=network.port, 
                             description=name, service='nodemcu', mac=mac}
        local ok, result = pcall(mdns.register , host, config)
        if (ok) then
            print('mdns ready')
        else
            print('mdns fail')
        end
    end
    --sntp
    sntp.sync(nil, nil,
        function(code, info)
            status_sntp = (code or '')..','.. (info or '')
        end, 0)

end)

--listen
if (network.ip ~= nil) then
    print('\nlisten at:'..network)
    sv = net.createServer(net.TCP, 30)
    if (network.port == nil) then network.port = '80' end
    sv:listen(network.port, network.ip, function(conn)
        conn:on('receive', util.parse)
      end)
end

--button
require('button')
local count_reset = 0
local reset_timeout = 0
local pin_reset = 1
--press 3 time
function onReset ()
    if (gpio.read(pin_reset) == 0) then
        count_reset = count_reset + 1
        if (count_reset >= 2) then
            node.restore()
            node.restart()            
        end
    end

end
gpio.mode(pin_reset, gpio.INT, gpio.PULLUP)
gpio.trig(pin_reset, 'both', button.debounce(onReset))

local pin_ap = 2
function onSetup ()
    if (gpio.read(pin_ap) == 0) then
        if (wifi.getmode() == wifi.STATION) then
            wifi.setmode(wifi.STATIONAP, false)
        else
            wifi.setmode(wifi.STATION, false)
        --node.restart()
        end
    end
end
gpio.mode(pin_ap, gpio.INT, gpio.PULLUP)
gpio.trig(pin_ap, 'both', button.debounce(onSetup))

--sensor
local sensor = _type..'.lua'
if (file.exists(sensor)) then
    dofile(sensor)
end

--ddns, 10s update once
_ddns = {interval = 10000}
_ddns = util.read_config('ddns', _ddns)
local url_ip = 'http://ip.chinaz.com/getip.aspx'

local function url_ddns(ip)    
    return 'https://'.._ddns.user..':'.._ddns.password
                 ..'@www.dnsdynamic.org/api/?hostname='
                 .._ddns.host..'&myip='..ip
end

local update_interval = 0
local tmr_ddns = tmr.create()
tmr_ddns:register(1000, tmr.ALARM_AUTO,function()
    update_interval = update_interval + 1000
    if (_ddns.interval == nill) then _ddns.interval = 10000 end
    if (update_interval >= _ddns.interval) then
        http.get(url_ip, nil, function(code, data)
            if (code == 200) then
                local ok, url = pcall(url_ddns,data.ip)
                if (ok) then
                    http.get(url, nil, function(code, data)
                            pcall(print, 'ddns:' .. code)
                        end)
                end
            end
        end)
        update_interval = 0 --reset
    end
end)
tmr_ddns:start()

